package cn.kimming.wms.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.opensymphony.xwork2.ActionContext;

import cn.kimming.wms.dao.IEmployeeDAO;
import cn.kimming.wms.domain.Employee;
import cn.kimming.wms.domain.Permission;
import cn.kimming.wms.domain.Role;
import cn.kimming.wms.query.QueryObject;
import cn.kimming.wms.service.IEmployeeService;
import cn.kimming.wms.util.MD5;
import cn.kimming.wms.util.UserContext;

@Service("employeeService")
public class EmployeeServiceImpl implements IEmployeeService{
	
	@Autowired
	private IEmployeeDAO employeeDAO;
	
	@Override
	public void save(Employee e) {
		e.setPassword(MD5.getMD5(e.getPassword()));
		employeeDAO.save(e);
	}

	@Override
	public void update(Employee e) {
		employeeDAO.update(e);
	}

	@Override
	public void delete(Long id) {
		employeeDAO.delete(employeeDAO.get(id));
	}

	@Override
	public Employee get(Long id) {
		return employeeDAO.get(id);
	}

	@Override
	public List<Employee> list() {
		return employeeDAO.list();
	}

	@Override
	public List<Employee> query(QueryObject qo) {
		return employeeDAO.query(qo);
	}

	@Override
	public void login(String username, String password) {
		password = MD5.getMD5(password);
		Employee user = employeeDAO.login(username, password);
		if (user == null) {
			throw new RuntimeException("亲, 用户名或密码错误!");
		}
		//将用户存入session
		UserContext.putUser(user);
		//将用户权限表达式存入session
		Set<String> permissionSet = new HashSet<>();
		List<Role> rs = user.getRoles();
		for (Role r : rs) {
			List<Permission> ps = r.getPermissions();
			for (Permission p : ps) {
				permissionSet.add(p.getExpression());
			}
		}
		UserContext.putPemissions(permissionSet);
	}
	
}
